﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using qkview.Filters;
using qkview.Models;
using WebMatrix.WebData;

namespace qkview.Controllers
{
    [InitializeSimpleMembership]
    public class BoardController : Controller
    {
        private QKVEntities db = new QKVEntities();

        //
        // GET: /Board/
        public ActionResult Index(string username)
        {

            ViewBag.ReqestedUserName = username; 

            if (User.Identity.IsAuthenticated && User.Identity.Name == username)
            {
                ViewBag.IsEdit = true;
            }
            else { 
                ViewBag.IsEdit = false;                
            }
            IEnumerable<SelectListItem> items =db.Categories.AsEnumerable().Select(x => new SelectListItem { Text = x.Name , Value = x.CategoryID.ToString() });
            ViewBag.Categories = items;
            
            string displayName =  db.UserProfiles.FirstOrDefault(x => x.UserName == username).Name;
            ViewBag.DisplayName = String.IsNullOrEmpty(displayName) ? username : displayName;  
            //ViewBag.DisplayName = username;
            return View(new BoardModels()
            {
                ListModel =
                    db.Boards.Where(x => x.UserProfile.UserName == username).ToList(),
                CreateModel = ViewBag.IsEdit ? new Board()  : null
            });               
                
        }

        //
        // GET: /Board/Details/5
        public ActionResult Details(int id = 0)
        {
            Board board = db.Boards.Find(id);
            if (board == null)
            {
                return HttpNotFound();
            }
            return View(board);
        }       

        //
        // POST: /Board/Create
        [Authorize] 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Create(Board board)
        {
            //Don't use this time, It is not created yet we are assigning userid right now.
            //if (board.UserProfile.UserName != WebSecurity.CurrentUserName) {
            //    return HttpNotFound(); 
            //}

            int allowedBoards = Common.GetUserSetting().TotalBoards;
            if (db.Boards.Count(x => x.UserID == WebSecurity.CurrentUserId) >= allowedBoards) {
                ModelState.AddModelError("", "Please upgrade your account to create more Boards.");
                return Json(new { errors = new List<string>() { "Please upgrade your account to create more Boards." } });
            }


            if (ModelState.IsValid)
            {
                String slug = Common.GenerateSlug(board.Title); 
                int slugSuffix = db.Boards.Count(x=>x.UserID == WebSecurity.CurrentUserId && x.URLSlug == slug);
                if (slugSuffix > 0) {
                    slug += "-" + slugSuffix; 
                }
                board.URLSlug = slug;
                board.UserID = WebSecurity.CurrentUserId;                
                board.IsPrivate = false; 
                board.CreatedDate = DateTime.UtcNow; 
                db.Boards.Add(board);
                db.SaveChanges();
               //return RedirectToRoute("Board", new { username = User.Identity.Name });
                return Json(new { success = true, redirect = Url.RouteUrl("Board", new { username = User.Identity.Name }) });
            }
            return Json(new { errors = new List<string>(){ "Invalid data"} });
        }

        //
        // GET: /Board/Edit/5
        [Authorize]        
        public ActionResult Edit(string id)
        {
            Board board = db.Boards.Find(Convert.ToInt32(Common.Decode(id)));
            if (board == null || board.UserProfile.UserName != WebSecurity.CurrentUserName) //not for other users
            {
                return HttpNotFound();
            }
            IEnumerable<SelectListItem> items = db.Categories.AsEnumerable().Select(x => new SelectListItem { Text = x.Name, Value = x.CategoryID.ToString(), Selected = ( x.CategoryID == board.CategoryID) });
            ViewBag.Categories = items;
            return View(board);
        }

        //
        // POST: /Board/Edit/5
        [Authorize]
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Edit(Board board)
        { 
            Board boardOrg = db.Boards.Find(board.BoardID);
            //not for other users

            if (boardOrg.UserID != WebSecurity.CurrentUserId)
            {
                return HttpNotFound();
            }
            if (ModelState.IsValid)
            {
               
                boardOrg.Title = board.Title;
                boardOrg.Description = board.Description;
                boardOrg.CategoryID = board.CategoryID;  
                db.Entry(boardOrg).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToRoute("Board", new { username = User.Identity.Name });
            }
            return View(board);
        }

        //
        // GET: /Board/Delete/5

        //public ActionResult Delete(string id)
        //{
        //    Board board = db.Boards.Find(Convert.ToInt32(Common.Decode(id)));
        //    //not for other users
        //    if (board == null || board.UserProfile.UserName != WebSecurity.CurrentUserName)
        //    {
        //        return HttpNotFound();
        //    }            
        //    return View(board);
        //}

        //
        // POST: /Board/Delete/5
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            Board board = db.Boards.Find(Convert.ToInt32(Common.Decode(id)));
            //not for other users
            if (board.UserID  != WebSecurity.CurrentUserId)
            {
                return Json(new { errors = new List<string>() { "You are not allowed to remove this board." } });
            }
            else
            {              
                db.Boards.Remove(board);
                db.SaveChanges();
                return Json(new { success = true });
            }
        }

       




        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}